package cn.kzgg.pet.service.impl;

import cn.kzgg.basic.service.impl.BaseServiceImpl;
import cn.kzgg.pet.domain.PetType;
import cn.kzgg.pet.mapper.PetTypeMapper;
import cn.kzgg.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author KZGG
 * @since 2022-06-25
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> queryTree() {
        //1.一次性查询出所有数据，放到内存 all
        List<PetType> petTypes = petTypeMapper.loadAll();
        //为了找到父亲，把整体部门数据转换成Map<id,deparent>
        Map<Long, PetType> allPetTypes = petTypes.stream().collect(Collectors.toMap(PetType::getId, petType -> petType));
        /*HashMap<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            //循环绑定
            allDepts.put(department.getId(),department);
        }*/
        //所有部门中找顶级部门
        List<PetType> firstPetTypes = new ArrayList<>();
        for (PetType temp : petTypes) {
            //没有父亲就说明是最大的
            if(temp.getPid()==null){
                //2.从所有数据中找出第一层firstDepts
                firstPetTypes.add(temp);
            }else {
                //3.如果不是第一层，找到上级并将自己放入上层children中
                PetType parent = allPetTypes.get(temp.getPid());
                if(parent!=null){
                    parent.getChildren().add(temp);

                }
            }
        }
        return firstPetTypes;
    }
}
